import { baseUrlApi, requestClient, type Result } from '#/api/request';
import { handleTree } from '#/api/utils/tree';
// 后台菜单数据类型
export interface MenuData {
  higherDeptOptions?: Record<string, unknown>[];
  id?: number; // id
  parent_id?: number; // 父级菜单ID,0:表示一级菜单
  name: string; // 名称
  app: string; // 应用名
  controller: string; // 控制名
  action: string; // 方法名
  param?: string; // 参数(暂无用)；例:id=3&p=3
  icon?: string; // 图标；不带前缀fa-，如fa-user => user
  remark?: string; // 备注
  status?: number; // 状态;1:显示;0:隐藏
  type?: number; // 类型;0:只作为菜单;1:有界面可访问菜单;2:无界面可访问菜单
  list_order?: number; // 排序
}

/** 后台菜单列表 */
export const getAdminMenus = async (istree = false) => {
  if (istree) {
    const {
      data: { list },
    } = await requestClient.get<Result>(baseUrlApi('/admin/menus'));
    // 过滤类型为2:无界面可访问菜单
    const menus = list.filter((item: any) => item.type !== 2);
    return handleTree(menus, 'id', 'parent_id');
  } else {
    return requestClient.get<Result>(baseUrlApi('/admin/menus'));
  }
};

/**
 * 添加后台菜单
 * @param data
 * @returns
 */
export const postAdminMenus = (data?: MenuData) => {
  return requestClient.post<Result>(baseUrlApi('/admin/menus'), data);
};

/**
 * 获取后台菜单信息
 * @param id
 * @returns
 */
export const getAdminMenusInfo = (id: number) => {
  return requestClient.get<Result>(baseUrlApi(`/admin/menus/${id}`));
};

/**
 * 编辑后台菜单
 * @param id
 * @param data
 * @returns
 */
export const putAdminMenus = (id: number, data?: MenuData) => {
  return requestClient.put<Result>(baseUrlApi(`/admin/menus/${id}`), data);
};

/**
 * 删除后台菜单
 * @param id
 * @returns
 */
export const deleteAdminMenus = (id: number) => {
  return requestClient.delete<Result>(baseUrlApi(`/admin/menus/${id}`));
};

/** 后台菜单排序 */
export const postAdminMenusListOrder = (data?: { list_orders: object }) => {
  return requestClient.post<Result>(
    baseUrlApi('/admin/menus/list/order'),
    data,
  );
};

/**
 * 导出后台菜单语言包
 */
export const postAdminMenusLangExport = () => {
  return requestClient.post<Result>(baseUrlApi(`/admin/menus/lang/export`));
};

/**
 * 导入新后台菜单
 */
export const postAdminMenusImport = (data: { app: string }) => {
  return requestClient.post<Result>(baseUrlApi(`/admin/menus/import`), data);
};
